package thread;

//模拟实现定时器

import java.util.Comparator;
import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask> {
    //任务啥时候执行
    private long time;

    //任务
    private Runnable runnable;

    public long getTime() {
        return time;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public MyTimerTask(Runnable runnable, long delay) {
        this.time = System.currentTimeMillis() + delay;
        this.runnable = runnable;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
}

//定时器本体
class MyTimer {
    PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    private Object locker = new Object();

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            MyTimerTask task = new MyTimerTask(runnable, delay);
            queue.offer(task);
            //每次新任务来了，都要唤醒扫描线程来根据情况更新最新的任务情况。
            locker.notify();
        }
    }

    public MyTimer() {
        Thread t1 = new Thread(() -> {
            while (true) {

                try {
                    synchronized (locker) {
                        /*if (queue.isEmpty()) {
                            continue;
                        }*/
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask task = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= task.getTime()) {
                            queue.poll();
                            task.getRunnable().run();
                        }else {
                            //Thread.sleep(task.getTime() - curTime);
                            //此处使用Sleep是不合适的，Sleep进入阻塞后会一直占用锁。
                            locker.wait(task.getTime() - curTime);
                        }
                    }
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
    }

}

public class Demo17 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1");
            }
        }, 1000);
        System.out.println("程序开始运行");

    }
}
